import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:grasp_flutter_app/utils/dao/user_dao.dart';
import 'package:grasp_flutter_app/utils/model/user.dart';
import '../utils/utils.dart';
import 'main_page.dart';

/// 欢迎页
class WelcomePage extends StatefulWidget {
  static final String name = "/";

  @override
  _WelcomePageState createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  bool hadInit = false;
  int buildRef = 0;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    initUserData();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (Consts.debug) print("build ${buildRef++}");
    SizeUtils.size = MediaQuery.of(context).size;

    return Scaffold(
      body: StoreBuilder<SysState>(builder: (context, store) {
        return Container(
          color: Styles.white,
          width: double.infinity,
          child: store.state.user != null ? Stack(
            children: <Widget>[
              new Center(
                child: Text(Utils.getLocale(context).name, style: Styles.largeLargeText),
              ),
              new Align(
                alignment: Alignment.bottomCenter,
                child: new Container(
                  child: Text(store.state.user == null ? "Version ${Consts.version}}" : "欢迎您, ${store.state.user.name}", style: Styles.smallSubText),
                  margin: EdgeInsets.only(bottom: SizeUtils.getAxisY(16.0)),
                ),
              )
            ],
          ) : Container(),
        );
      }),
    );
  }

  initUserData() {
    if (hadInit) {
      return;
    }
    hadInit = true;

    /// 防止多次进入
    Store<SysState> store = StoreProvider.of(context);

    UserDao.initUserInfo(store).then((res) {
      if (res != null) {
        // 初始化成功,进入主页
        if (Consts.debug) print("初始化成功,进入主页");
        new Future.delayed(const Duration(seconds: 2), () {
          goMain();
        });
      } else {
        if (Consts.debug) print("未登录");
        new Future.delayed(const Duration(seconds: 2), () {
          if (Consts.debug) print("自动登录");
          goLogin(store);
        });
      }
      return true;
    });
  }

  goLogin(Store store) async {
    await UserDao.login("yangyxd", "123456", store);
    goMain();
  }

  goMain() {
    Navigator.pushReplacementNamed(context, MainPage.name);
  }
}
